<template>
  <div style="display: flex;flex-direction: row">
    <div id="chart" style="width: 50%; height: 600px;border: 0px black solid"></div>

    <div style="display: flex;flex-direction: column;width: 50%">
      <Ranking :consultantsData="consultants" style="border: 0px black solid;" />
      <AppointmentChart />
    </div>

  </div>
</template>

<script lang="ts" setup>
import Ranking from './ranking.vue';
import { onMounted, ref } from 'vue'
import * as echarts from 'echarts';
import chinaJson from 'echarts/map/json/china.json';
import AppointmentChart from '@/views/dataAnalysis/AppointmentChart.vue'
import {mapService, ratingService} from '@/api/analysis.js'



const consultants=ref([])


onMounted(async () => {

  let ratRes=await ratingService()
  if (ratRes.code===200){
    consultants.value=ratRes.data
  }

  const mapRes=await mapService()
  //用户全国分布接口
  if (mapRes.code===200){
    console.log(mapRes.data)

    echarts.registerMap('China', chinaJson);

    let users = [];
    users=mapRes.data

    const provinceData: Record<string, { counselors: number; clients: number }> = {};

    users.forEach((user) => {
      const province = user.address;
      if (!provinceData[province]) {
        provinceData[province] = { counselors: 0, clients: 0 };
      }

      if (user.userType === 'counselor') {
        provinceData[province].counselors += 1;
      } else if (user.userType === 'client') {
        provinceData[province].clients += 1;
      }
    });

// 转换为 ECharts 可用格式
    const seriesData = Object.keys(provinceData).map((key) => ({
      name: key,
      value: provinceData[key].clients, // 来访者数量作为图表数据值
      counselors: provinceData[key].counselors, // 储存咨询师数量
    }));

    const chartElement = document.getElementById('chart');
    const myChart = echarts.init(chartElement!); // 确保类型安全

    const option = {
      title: {
        text: '中国用户分布图',
        subtext: '展示各省用户数与咨询师数',
        left: 'center',
      },
      tooltip: {
        trigger: 'item',
        formatter: function (params: any) {
          return `${params.name}<br/>来访者: ${params.value}<br/>咨询师: ${params.data.counselors || 0}`;
        },
      },
      visualMap: {
        min: 0,
        max: Math.max(...seriesData.map((item) => item.value)), // 根据最大值调整
        left: 'left',
        top: 'bottom',
        text: ['高', '低'],
        calculable: true,
        inRange: {
          color: ['#ffeb3b', '#ff9800', '#f44336'], // 颜色渐变
        },
      },
      series: [
        {
          name: '用户数',
          type: 'map',
          map: 'China',
          label: {
            show: true,
          },
          data: seriesData,
        },
      ],
    };

    // 使用指定的配置项和数据显示图表。
    myChart.setOption(option);
  }


});


</script>

<style>
/* 可以添加全局样式 */

</style>
